<?php
    require '../Include/BDMySQL.class.php';
    $MySQL = new BDMySQL();
    $MySQL->ligarBD() or die;
    
    header('Content-Type: application/xml;'); 
    
    $XML = new SimpleXMLElement_Plus('<?xml version="1.0" encoding="utf-8"?> <XSWeeks
        xmlns="http://rpmestre.net/xscrawler"
        xmlns:XSWeeks = "http://www.w3.org/2001/XMLSchema-instance"
        XSWeeks:schemaLocation = "http://rpmestre.net/xscrawler XSWeeksSchema.xsd">
        </XSWeeks>');
   $XML->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xslt/weeks_page.xslt"'); 
   

    $sql =" select e.descricao, e.idepoca, j.idEdicaoCompeticao, comp.descricao,  j.`jornada`, j.descricao_jornada, max(dia)  
            from jogos j, edicoescompeticoes c, epocas e, competicoes comp
            where j.`idEdicaoCompeticao` =  (select max(idEdicaoCompeticao) from edicoescompeticoes where idCompeticao=1)
            and j.idEdicaoCompeticao = c.idEdicaoCompeticao
            and  c.idepoca = e.idepoca
            and c.idcompeticao = comp.idcompeticao
            and j.dia< DATE_FORMAT(now(), '%Y-%m-%d') and j.activo = 1
            group by j.idEdicaoCompeticao, j.jornada
            order by j.idEdicaoCompeticao desc, j.jornada desc";
    
    $query = mysql_query($sql);
    $weeksList = array();
	while ($row = mysql_fetch_array($query, MYSQL_NUM)) 
	{
        $XML_week = $XML->addChild('week');
        
		$XML_season = $XML_week->addChild('season', $row[0]);
        $XML_season->addAttribute('id', 's_'.$row[1]);
        
		$XML_competition = $XML_week->addChild('competition', $row[3]);
        $XML_competition->addAttribute('id', 'c_'.$row[2]);
        
        $XML_week->addAttribute('id', 'w_'.$row[4]);
		$XML_week->addChild('weekDescription', $row[5]==''?$row[4]:$row[5]);
        $XML_week->addChild('lastDay', $row[6]);        			
    }
    echo $XML->asXML();
    
    
    class SimpleXMLElement_Plus extends SimpleXMLElement 
    {
        public function addProcessingInstruction( $name, $value )
        {
            // Create a DomElement from this simpleXML object
            $dom_sxe = dom_import_simplexml($this);
           
            // Create a handle to the owner doc of this xml
            $dom_parent = $dom_sxe->ownerDocument;
           
            // Find the topmost element of the domDocument
            $xpath = new DOMXPath($dom_parent);
            $first_element = $xpath->evaluate('/*[1]')->item(0);
           
            // Add the processing instruction before the topmost element           
            $pi = $dom_parent->createProcessingInstruction($name, $value);
            $dom_parent->insertBefore($pi, $first_element);
        }
    }
 ?>